//
//  DetailsOfTheMeetingFromViewController.m
//  Gxj
//
//  Created by 刘伟 on 2017/9/18.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "DetailsOfTheMeetingFromViewController.h"
#import "DetailsOfMeetingFromMeeting.h"
#import "DetailsOfMeetingFromTableViewCell.h"
#import "DetailsOfMeetingFromFootView.h"
#import "CommentariesFromModel.h"
#import <UITableView+SDAutoTableViewCellHeight.h>

@interface DetailsOfTheMeetingFromViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    DetailsOfMeetingFromMeeting *_detailsOfMeetingView;
    DetailsOfMeetingFromFootView *_detailsOfMeetingFootView;
//    CommentariesFromModel *_commentariesModel;
}
@property (nonatomic,strong) UITableView *tableView;
@property(nonatomic, strong) UILabel * navTitleLbl;
@property(nonatomic, strong) UIButton *navTitleBtn;
@property (nonatomic,strong) UIView *navTitleView;
@property (nonatomic,strong) NSMutableArray *mutableArray;

//导航条上拉隐藏下拉显示
@property (nonatomic, assign) CGFloat borderNum;
@property (nonatomic ,assign) NSInteger firstComeInNum;
@end

@implementation DetailsOfTheMeetingFromViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showDetailsOfTheMeeting];
    self.mutableArray = [NSMutableArray array];
    [self initData];
    [self.tableView reloadData];
}

- (void)showDetailsOfTheMeeting
{
    [self.view addSubview:self.tableView];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"tbg"]forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle=UIBarStyleBlackTranslucent;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:17]};
    
    _detailsOfMeetingView = [[DetailsOfMeetingFromMeeting alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(281))];
    _detailsOfMeetingView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.tableHeaderView = _detailsOfMeetingView;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;// 去掉所有cell的分割线
    
    _detailsOfMeetingFootView = [[DetailsOfMeetingFromFootView alloc] initWithFrame:CGRectMake(0, UIScreenHeight - 113, UIScreenWidth, 49)];
    _detailsOfMeetingFootView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:_detailsOfMeetingFootView];
    
    [self navgationBarSet];
}

- (void)getHeadViewJson
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dict = @{@"userid":userid,
                           @"meetingid":@""
                           };
    
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/meeting/meetinginfo",MAIN_URL] parameters:dict success:^(NSDictionary *dic) {
        
    } failure:^(NSError *error) {
        
    }];
}

/*!
 *    解析本地json数据
 */
- (void)initData
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"TextInfo" ofType:@"json"];
    NSString *jsonContent=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if (jsonContent != nil)
    {
        NSData *jsonData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:&err];
        NSArray *textList = [dic objectForKey:@"textList"];
        for (NSDictionary *dict in textList)
        {
            CommentariesFromModel *entity = [[CommentariesFromModel alloc]initWithDict:dict];
            if (entity)
            {
                [self.mutableArray addObject:entity];
                [self.tableView reloadData];
            }
            [self.tableView reloadData];
        }
        if(err)
        {
            NSLog(@"json解析失败：%@",err);
        }
    }
}

#pragma mark - 导航条
- (void)navgationBarSet
{
    self.title = @"会议详情";
    
    UIButton *rightItem = [UIButton buttonWithType:UIButtonTypeCustom];
    rightItem.frame = CGRectMake(0, 0, kWidthScale(18), kHeightScale(18));
    [rightItem setImage:[UIImage imageNamed:@"xialagenduo"] forState:0];
    rightItem.contentMode = UIViewContentModeScaleAspectFit;
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItem];
    
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    /* 导航标题**/
    // 导航背景视图
    UIView *navBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidthScale(200), kHeightScale(30))];
    self.navigationItem.titleView = navBackView;
    
    UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidthScale(200), kHeightScale(30))];
    titleLbl.text = @"会议详情";
    [titleLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:17]];
    titleLbl.textColor = [UIColor whiteColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [navBackView addSubview:titleLbl];
    _navTitleLbl = titleLbl;
    
    UIButton *titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kWidthScale(200), kHeightScale(30))];
    [titleBtn setTitle:@"再近不过信仰" forState:UIControlStateNormal];
//    [titleBtn setImage:[UIImage imageNamed:@"touxiang"] forState:UIControlStateNormal];
//    titleBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, kWidthScale(20));
    titleBtn.contentMode = UIViewContentModeScaleAspectFit;
    
    titleBtn.titleLabel.font = [UIFont systemFontOfSize:kWidthScale(15)];
    [titleBtn setTitleColor:[UIColor whiteColor] forState:0];
//    [navBackView addSubview:titleBtn];
//    _navTitleBtn = titleBtn;
    
    UIView *backHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidthScale(200), kHeightScale(30))];
    UIButton *userHead = [[UIButton alloc] initWithFrame:CGRectMake(kWidthScale(30), kHeightScale(6), kWidthScale(18), kHeightScale(18))];
    [userHead setImage:[UIImage imageNamed:@"toixiang"] forState:0];
    [backHeadView addSubview:userHead];
    [backHeadView addSubview:titleBtn];
    
    [navBackView addSubview:backHeadView];
    _navTitleView = backHeadView;
    // 先让带图片的导航视图隐藏
//    _navTitleBtn.alpha = 0;
    _navTitleView.alpha = 0;
    _borderNum = 15.f;
    _firstComeInNum = 0;
}

#pragma mark -导航条设置
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    _firstComeInNum ++;
    if (_firstComeInNum >2) {
        // 表格 y 的滑动位置
        CGFloat contentOffset = scrollView.contentOffset.y ;
//        NSLog(@"contentOffset :%lf",contentOffset);
        if (contentOffset <0.f) { // y的位置小于0 ，不进行下面的操作 直接退出该方法
            return;
        } else if (contentOffset <(_borderNum)) { // y 小于 64 ，则显示 titleLbl ，并根据y的大小来改变titleLbl的透明度
            _navTitleLbl.alpha = (_borderNum - contentOffset )/ _borderNum;
            _navTitleView.alpha = 0.f;
        } else if (contentOffset >_borderNum) {
            _navTitleLbl.alpha = 0.f;
            _navTitleView.alpha = (contentOffset -_borderNum )/_borderNum;
        } else if (contentOffset == _borderNum) {
            _navTitleLbl.alpha = 0.f;
            _navTitleView.alpha = 0.f;
        }
//        NSLog(@"%lf",contentOffset);
    }
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger inter;
    if (section == 0) {
        inter = 1;
    }else if (section == 1){
        inter = [self.mutableArray count];
    }
    return inter;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat loat;
    if (indexPath.section == 0) {
        loat = kHeightScale(231);
    }else{
        CommentariesFromModel *entity = nil;
        if ([self.mutableArray count] > indexPath.row)
        {
            entity = [self.mutableArray objectAtIndex:indexPath.row];
        }
        //根据isShowMoreText属性判断cell的高度
        if (entity.isShowMoreText)
        {
            loat = [DetailsOfMeetingFromTableViewCell cellMoreHeight:entity];
        }
        else
        {
            loat = [DetailsOfMeetingFromTableViewCell cellDefaultHeight:entity];
        }
    }
    return loat;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat loat;
    if (section == 0) {
        loat = 25;
    }else{
        loat = 25;
    }
    return loat;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [UIView new];
    
    NSArray *arr = @[@"抢位",@"评论人数"];
    
    UIImageView *leftImg = [[UIImageView alloc] init];
    leftImg.image = [UIImage imageNamed:@"fanhui"];
    // 填充
    leftImg.contentMode = UIViewContentModeScaleAspectFit;
    [view addSubview:leftImg];
    
    UILabel * lab2 = [[UILabel alloc]init];
    lab2.textAlignment = 0;
    lab2.font = [UIFont boldSystemFontOfSize:kWidthScale(12)];
    lab2.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1];
    lab2.text = arr[section];
    [lab2 updateLayout];
    [view addSubview:lab2];
    
    lab2.sd_layout
    .centerYEqualToView(view)
    .leftSpaceToView(view, kWidthScale(15))
    .autoHeightRatio(0);
    [lab2 setSingleLineAutoResizeWithMaxWidth:kWidthScale(80)];
    
    leftImg.sd_layout
    .centerYEqualToView(lab2)
    .rightSpaceToView(view,kWidthScale(15))
    .widthIs(kWidthScale(6))
    .heightIs(kHeightScale(11));
    
    if (section == 0) {
        leftImg.hidden = YES;
    }else{
        leftImg.hidden = NO;
    }
    
    view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    //创建一个手势进行点击，这里可以换成button
    
    UIButton * but = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(25))];
    but.tag = 300+section;
    but.backgroundColor = [UIColor clearColor];
    [but addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:but];
    
    return view;
}

-(void)click:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    
    switch (btn.tag) {
        case 300:
            
            break;
            
        case 301:
            NSLog(@"点击了评论人数");
            break;
            
        default:
            break;
    }
}

#pragma mark - tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@""];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(kWidthScale(33), kHeightScale(15), kWidthScale(312), kHeightScale(201));
        imageView.image = [UIImage imageNamed:@"huiyizhuo"];
        [cell addSubview:imageView];
        return cell;
    }
    else if (indexPath.section == 1){
        DetailsOfMeetingFromTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"details"];
        
        if (!cell)
        {
            cell = [[DetailsOfMeetingFromTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"details"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if ([self.mutableArray count] > indexPath.row)
        {
            //防止数组越界
            cell.model = [self.mutableArray objectAtIndex:indexPath.row];
        }
        //自定义cell的回调，获取要展开/收起的cell。刷新点击的cell
        cell.showMoreTextBlock = ^(UITableViewCell *currentCell){
            NSIndexPath *indexRow = [_tableView indexPathForCell:currentCell];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexRow, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        
        return cell;
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - kHeightScale(54)) style:UITableViewStyleGrouped];
        
        _tableView.delegate = self;
        
        _tableView.dataSource = self;
    }
    return _tableView;
}

@end
